package common.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import common.hibernate.service.BaseService;
import common.rbac.po.User;

/**
 * 
 * 登陆验证过滤器
 */
public class MyAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

	protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

	private BaseService bs;

	public BaseService getBs() {
		return this.bs;
	}

	public void setBs(BaseService bs) {
		this.bs = bs;
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		if (!request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}

		String username = obtainUsername(request);
		String password = obtainPassword(request);

		// 验证用户账号与密码是否正确
		username = username.trim();
		User users = (User) this.bs.findOne("from User adm where adm.name=? and enabled = ?", username, true);
		// 通过session把用户对象设置到session中
		request.getSession().setAttribute(Constant.SESSION_USER, users);

		// 实现验证
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
		// 允许设置用户详细属性
		setDetails(request, authRequest);
		// 运行
		return this.getAuthenticationManager().authenticate(authRequest);
	}

	@Override
	protected String obtainUsername(HttpServletRequest request) {
		String obj = request.getParameter(Constant.USERNAME);
		return StringUtils.trimToEmpty(obj);
	}

	@Override
	protected String obtainPassword(HttpServletRequest request) {
		String obj = request.getParameter(Constant.PASSWORD);
		return StringUtils.trimToEmpty(obj);
	}

	@Override
	protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
		super.setDetails(request, authRequest);
	}
}
